import * as React from 'react';
import { connect } from 'react-redux';

import './VideoPlayer.scss';

interface VideoPlayerProps {
  videoUri: any;
  isTiny: boolean;
}

interface VideoPlayerState {
  isPlaying: boolean;
}

class VideoPlayer extends React.PureComponent<VideoPlayerProps, VideoPlayerState> {
  videoPlayer: any;
  static inPlaySource: any;
  static defaultProps: VideoPlayerProps = {
    videoUri: '',
    isTiny: true,
  };
  constructor(props: VideoPlayerProps) {
    super(props);

    this.state = {
      isPlaying: false,
    };
  }

  handleVideoPlay = () => {
    if (this.videoPlayer.paused) {
      if (VideoPlayer.inPlaySource && !VideoPlayer.inPlaySource.videoPlayer.paused) {
        VideoPlayer.inPlaySource.handleVideoPlay();
      }
      VideoPlayer.inPlaySource = this;
      this.videoPlayer.play();
    } else {
      VideoPlayer.inPlaySource = null;
      this.videoPlayer.pause();
    }

    this.setState({
      isPlaying: !this.videoPlayer.paused,
    });
  };

  componentWillUnmount() {
    this.handlePause();
  }

  handlePause = () => {
    this.setState({
      isPlaying: false,
    });
  };

  handleEnded = () => {
    this.setState({
      isPlaying: false,
    });
    VideoPlayer.inPlaySource = null;
  };

  savePlayerRef = (ref: any) => {
    this.videoPlayer = ref;
  };

  render() {
    const { videoUri, isTiny } = this.props;
    const { isPlaying } = this.state;
    const vSize = isTiny ? 200 : 400;

    return (
      <div className="card-item-player" style={{ position: 'relative' }}>
        <video
          ref={this.savePlayerRef}
          src={videoUri}
          onEnded={this.handleEnded}
          onPause={this.handlePause}
          onClick={this.handleVideoPlay}
          controls={isPlaying}
          style={{
            objectFit: 'fill',
            width: vSize,
            height: vSize,
          }}
        />
        {!isPlaying && (
          <button onClick={this.handleVideoPlay} className="circle-video-player">
            <svg width="64px" height="64px" viewBox="0 0 32 32">
              <circle cx="16" cy="16" r="14.5" className="circle-media-player__background" />
              <circle cx="16" cy="16" r="14.5" className="circle-media-player__foreground" />
              <polygon
                points="13.083,11.5 20.583,16 13.083,20.5 "
                className="circle-media-player__play"
              />
            </svg>
          </button>
        )}
      </div>
    );
  }
}

interface OwnProps {
  videoUri: any;
  isTiny: boolean;
}

function mapStateToProps(state: any, ownProps: OwnProps) {
  const { videoUri, isTiny } = ownProps;
  return {
    videoUri,
    isTiny,
  };
}

export default connect(mapStateToProps)(VideoPlayer);
